<?php

/**
 *
 * Config(系统配置文件)
 *
 */
class WapAction extends PublicAction {

    protected $db;
    protected $wap_conf = array();

    function _initialize()
    {
        parent::_initialize();

        if (F('Wapconfig_'.LANG_NAME)) {
            $this->wap_conf =  F('Wapconfig_'.LANG_NAME);
        } else {
            $this->updateWapCache();
            $this->wap_conf =  F('Wapconfig_'.LANG_NAME);
        }
    }


    public function config()
    {
        if (IS_POST) {
            foreach($_POST as $key=>$value){
                $data['value']=$value;
                M('WapConfig')->where("lang=".LANG_ID." AND varname='".$key."'")->save($data);
            }

            //更新手机配置缓存
            $this->updateWapCache();

            $this->success('保存成功！');
        } else {
            $data = M('WapConfig')->where('lang='.LANG_ID)->select();
            $wap_config = array();
            foreach ($data as $val) {
                $wap_config[$val['varname']] = $val['value'];
            }

            $yzh_auth_key = sysmd5(C('ADMIN_ACCESS').$_SERVER['HTTP_USER_AGENT']);
            $yzh_auth = authcode('1-1-0-1-jpeg,jpg,png,gif-3-0', 'ENCODE',$yzh_auth_key);

            $this->assign('yzh_auth',$yzh_auth);
            $this->assign('wap_config',$wap_config);
            $this->display();
        }
    }

    function slide()
    {
        $map['lang']=array('eq',LANG_ID);
        $list = D('WapSlide')->where($map)->order("sort ASC ,id DESC ")->select();
        $this->assign('list', $list);
        $this->display();
    }

    function editslide(){

        $model = D('WapSlide');

        $id = I('get.id');
        $slide = $model->find($id);

        //isadmin,more,isthumb,file_limit,file_types,file_size,moduleid,
        $yzh_auth_key = sysmd5(C('ADMIN_ACCESS').$_SERVER['HTTP_USER_AGENT']);
        $yzh_auth = authcode('1-1-0-10-jpeg,jpg,png,gif-5-230', 'ENCODE',$yzh_auth_key);
        $this->assign('yzh_auth',$yzh_auth);


        if (IS_POST) {
            if (false === $model->create()) {
                $this->error($model->getError());
            }

            if (false !== $model->save()) {

                if($_POST['aid']){
                    $Attachment = M('attachment');
                    $aids = implode(',',$_POST['aid']);
                    $data['id']= $_POST['id'];
                    $data['status']= '1';
                    $Attachment->where("aid in (".$aids.")")->save($data);
                }
                $this->success('提交成功');
            } else {
                $this->success('提交失败: '.$model->getDbError());
            }
            exit;
        }
        $this->assign ( 'fid', $fid );
        $this->assign ( 'vo', $slide );

        $this->display();
    }

    function addslide(){

        $model = D('WapSlide');

        //isadmin,more,isthumb,file_limit,file_types,file_size,moduleid,
        $yzh_auth_key = sysmd5(C('ADMIN_ACCESS').$_SERVER['HTTP_USER_AGENT']);
        $yzh_auth = authcode('1-1-0-10-jpeg,jpg,png,gif-5-230', 'ENCODE',$yzh_auth_key);
        $this->assign('yzh_auth',$yzh_auth);


        if (IS_POST) {
            if (false === $model->create()) {
                $this->error($model->getError());
            }

            if (false !== $model->add()) {

                if($_POST['aid']){
                    $Attachment = M('attachment');
                    $aids = implode(',',$_POST['aid']);
                    $data['id']= $_POST['id'];
                    $data['status']= '1';
                    $Attachment->where("aid in (".$aids.")")->save($data);
                }
                $this->success('提交成功');
            } else {
                $this->success('提交失败: '.$model->getDbError());
            }
            exit;
        }

        $this->display();
    }

    function slidesort(){

        $model = M ('WapSlide');
        $ids = $_POST['sort'];
        foreach($ids as $key=>$r) {
            $data['sort']=$r;
            $model->where('id='.$key)->save($data);
        }
        $this->success (L('do_ok'));
    }

    function updateWap()
    {
        $data = array();
        foreach($_POST['youshi_title'] as $key=>$value) {

            $data[$key]['title'] = $value;
            $data[$key]['content'] = $_POST['youshi_content'][$key];
        }

        $f = M('WapConfig')->where("varname='index_youshi'")->save(array('value'=>json_encode($data)));

        $this->updateWapCache();

        $file1 = TMPL_PATH.'Wap/Default/Index_youshi.html';

        file_put_contents($file1,htmlspecialchars_decode(stripslashes($html_youshi)));

    }


    //手机导航
    function cat()
    {
        $categorys = M('Category')->where('parentid=0 and lang='.LANG_ID)->order('listorder')->select();
        //获取所有菜单
        import('@.ORG.Tree');
        $tree = new Tree();
        $data_list = $tree->toFormatTree($categorys,'catname','id','parentid');

        $this->assign('list', $data_list);
        $this->display();
    }

    function editcat()
    {
        $model = M('Category');

        if (IS_POST) {

            if (false === $model->create()) {
                $this->error($model->getError());
            }

            if (false !== $model->save()) {
                if($_POST['aid']) {
                    $Attachment = M('attachment');
                    $aids = implode(',',$_POST['aid']);
                    $data['moduleid'] = 11;
                    $data['catid']    = $_POST['id'];
                    $data['status']   = '1';
                    $Attachment->where("aid in (".$aids.")")->save($data);
                }

                //更新缓存
                $this->updateWapCache();

                $this->assign('jumpUrl', U('Wap/Cat') );
                $this->success(L('edit_ok'));
            } else {
                $this->success(L('edit_error').': '.$model->getDbError());
            }
        } else {
            $id = I('get.id', 0, 'intval');

            foreach((array)$this->Urlrule as $key =>$r){
                if($r['ishtml'])
                    $Urlrule[$key]=$r;
            }

            $this->assign('Urlrule', $Urlrule);

            $attach['moduleid'] = $info['moduleid'];
            $attach['file_size'] = '2MB';
            $attach['file_limit'] = 10;
            $attach['file_types'] = '*.jpeg;*.jpg;*.png;*.gif';
            $attach['isthumb'] = 0;
            $attach['isadmin'] = $this->isadmin;
            $yzh_auth_key = sysmd5(C('ADMIN_ACCESS').$_SERVER['HTTP_USER_AGENT']);
            $yzh_auth = authcode(json_encode($attach), 'ENCODE', $yzh_auth_key);

            $this->assign('yzh_auth',$yzh_auth);

            $templates = $this->template_file();
            $this->assign('templates', $templates);

            $record = $model->find($id);

            if(empty($id) || empty($record)){
                $this->error(L('do_empty'));
            }

            $this->assign('vo', $record);

            $this->display();
        }
    }


    public function ajax_updatecat(){

        $id = intval(trim($_POST['id']));

        $model = M('Category');

        if (!empty($_POST['is_wap_menu'])){
            $num = $model->where('parentid=0 and is_wap_menu=1 and lang='.LANG_ID)->count('id');

            if ($num>6){
                $this->error('手机导航栏目不能超过7个');
            }
        }

        $_POST['updatetime'] = time();
        unset($_POST['id']);
        $model->save($_POST,array('where'=>'id="'.$id.'"'));
        $this->success('更新成功');
    }

    //外观设置
    function preview()
    {
        $data = M('WapConfig')->select();

        $config = array();
        foreach ($data as $val) {
            $config[$val['varname']] = $val['value'];
        }

        $index_youshi = json_decode($config['index_youshi'], true);
        $this->assign('index_youshi', $index_youshi);
        $this->assign('index_aboutus', $config['index_aboutus']);

        $this->assign($this->sysConfig);
        $this->display();
    }


    function editblock()
    {
        $blockname = I('blockname');

        if (LANG_NAME != $this->sysConfig['DEFAULT_LANG']) {
            $default_theme = $this->sysConfig['DEFAULT_M_THEME'] . '_' . $_GET['l'];
        } else {
            $default_theme = $this->sysConfig['DEFAULT_M_THEME'];
        }
        
        $filename = './Themes/Wap/'.$default_theme.'/Block/'.$blockname.'.html';

        $content = file_get_contents($filename);

        $this->assign('content', $content);
        $this->assign('blockname', $blockname);
        $this->display();
    }

    function updateblock()
    {
        $content = $_POST['blockcontent'];
        $blockname = $_POST['blockname'];

        if (LANG_NAME != $this->sysConfig['DEFAULT_LANG']) {
            $default_theme = $this->sysConfig['DEFAULT_M_THEME'] . '_' . $_GET['l'];
        } else {
            $default_theme = $this->sysConfig['DEFAULT_M_THEME'];
        }
        
        $filename = './Themes/Wap/'.$default_theme.'/Block/'.$blockname.'.html';

        file_put_contents($filename, $content);

        $this->success('编辑成功');
    }

    function theme()
    {

        $tplpath = './Themes/Wap/';

        $filed = glob($tplpath.'*');
        foreach ($filed as $key=>$v) {
            $arr[$key]['name'] =  basename($v);
            if(is_file($tplpath.$arr[$key]['name'].'/preview.jpg')){
                $arr[$key]['preview'] = $tplpath.$arr[$key]['name'].'/preview.jpg';
            }else{
                $arr[$key]['preview'] = __ROOT__.'/Public/images/nopic.jpg';
            }

            if ($this->Conf['DEFAULT_M_THEME'] == $arr[$key]['name']) {
                $arr[$key]['use']=1;
            }
        }

        $this->assign('themes',$arr);
        $this->display();
    }

    function chosetheme()
    {
        $theme = $_GET['theme'];
        if($theme){
            $Model = M('Config');
            $Model->where("varname='DEFAULT_M_THEME'")->setField('value',$theme);
            $this->updateWapCache();
            $this->success(L('do_ok'));
        }else{
            $this->error(L('do_empty'));
        }
    }


    function updateWapCache()
    {
        //更新手机配置缓存
        $lang = F('Lang');

        foreach ((array)$lang as $key=>$r) {
            $wapconfig = array();
            $data = M('WapConfig')->where('lang='.$r['id'])->select();
            foreach ($data as $val) {
                $wapconfig[$val['varname']] = $val['value'];
            }
            F('Wapconfig_'.$key, $wapconfig);
        }
    }

    function template_file($module='',$path='',$ext='html')
    {
        $path = $path ? $path : TMPL_PATH.'Wap/'.$this->sysConfig['DEFAULT_M_THEME'].'/';

        $tempfiles = dir_list($path,$ext);

        foreach ($tempfiles as $key=>$file) {

            $dirname = basename($file);

            if ($module) {
                if(strstr($dirname,$module.'_')) {
                    $arr[$key]['name'] =  substr($dirname,0,strrpos($dirname, '.'));
                    $arr[$key]['value'] =  substr($arr[$key]['name'],strpos($arr[$key]['name'], '_')+1);
                    $arr[$key]['filename'] = $dirname;
                    $arr[$key]['filepath'] = $file;
                }
            } else {
                $arr[$key]['name'] = substr($dirname,0,strrpos($dirname, '.'));
                $arr[$key]['value'] = substr($arr[$key]['name'],strpos($arr[$key]['name'], '_')+1);
                $arr[$key]['filename'] = $dirname;
                $arr[$key]['filepath'] = $file;
            }
        }
        return  $arr;
    }
}